mybatis-枚举类型的typeHandler&自定义枚举类型typeHandler

MyBatis内部提供了两个转化枚举类型的typeHandler给我们使用。

  • org.apache.ibatis.type.EnumTypeHandler 是使用枚举字符串名称作为参数传递的
  • org.apache.ibatis.type.EnumOrdinalTypeHandler 是使用整数下标作为参数传递的

数据库脚CREATE TABLE `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `gender` int(11) DEFAULT NULL, --对应Gender枚举类
  `hobby` varchar(255) DEFAULT NULL, --对用Hobby枚举类
`member` int(11) DEFAULT NULL, --对应Member枚举类
`userAge`
int(11) DEFAULT NULL, `userAddress` varchar(200) DEFAULT NULL, `reg_time` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

 

创建三个枚举类Gender、Hobby、Member

package com.yihaomen.mybatis.enums;

public enum  Gender {

    MALE(1, "男性"), FEMALE(2, "女性");
    private int code;
    private String name;

    Gender(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static Gender getGender(int code) {
        for(Gender gender : Gender.values()) {
            if(gender.getCode() == code) {
                return gender;
            }
        }
        return null;
    }

}

 

package com.yihaomen.mybatis.enums;

public enum Hobby {
    FOOTBALL(1,"足球"), BASKETBALL(2, "篮球");
    private int code;
    private String name;

    Hobby(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public static Hobby getHobby(int code) {
        for(Hobby h : Hobby.values()) {
            if(h.getCode() == code) {
                return h;
            }
        }
        return null;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

package com.yihaomen.mybatis.enums;

public enum Member {
    FATHER(1,"爸爸"), MOTHER(2,"妈妈");
    private int code;
    private String name;

    Member(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static Member getMember(int code) {
        for(Member member : Member.values()) {
            if(member.getCode() == code) {
                return member;
            }
        }
        return null;
    }
}

 

写model层

package com.yihaomen.mybatis.model;

import com.yihaomen.mybatis.enums.Gender;
import com.yihaomen.mybatis.enums.Hobby;

import java.util.Date;

public class User {
    private int id;
    private String userName;
    private String userAge;
    private Gender gender;
private Member member;
private Hobby hobby;
private String userAddress; private Date regTime; setters()&getters()... }

自定义typeHandler

package com.yihaomen.mybatis.type;

import com.yihaomen.mybatis.enums.Member;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyMemberTypeHandler implements TypeHandler<Member> {
    public void setParameter(PreparedStatement ps, int i, Member parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getCode());
    }

    public Member getResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);
        return Member.getMember(code);
    }

    public Member getResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        return Member.getMember(code);
    }

    public Member getResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        return Member.getMember(code);
    }
}

  

写DAO层

User.xml

<?xml version="1.0" encoding="UTF-8" ?>
<resultMap id="resultListUser" type="User">
        <id column="id" property="id" />
        <result column="userName" property="userName" />
        <result column="userAge" property="userAge" />
<!----> <result column="gender" property="gender" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/> <result column="hobby" property="hobby" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
     <result column="member" property="member" typeHandler="com.yihaomen.mybatis.type.MyMemberTypeHandler"/><!--自定义枚举typeHandler-->
<result column="userAddress" property="userAddress" /> <result column="reg_time" property="regTime" javaType="java.util.Date" jdbcType="VARCHAR" typeHandler="com.yihaomen.mybatis.type.MyDateTypeHandler"/> </resultMap> <select id="selectUserById2" parameterType="long" resultMap="resultListUser"> select userName, gender, hobby from user where id = #{id}</select> <insert id="addUser2" parameterType="User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user(userName, userAge, gender, hobby, userAddress, reg_time) VALUES(#{userName},#{userAge},#{gender},#{hobby},#{userAddress}, #{regTime,javaType=Date,jdbcType=VARCHAR,typeHandler=com.yihaomen.mybatis.type.MyDateTypeHandler}) </insert>

 

UserMapper

package com.yihaomen.mybatis.dao;

import com.yihaomen.mybatis.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    public List<User> selectUserById2(Long id);
    public int addUser2(User user);
}

 

在configuration.xml注册typeHandler

<typeHandlers>
        <typeHandler handler="com.yihaomen.mybatis.type.MyDateTypeHandler" />
        <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
                     javaType="com.yihaomen.mybatis.enums.Gender" />
        <typeHandler handler="org.apache.ibatis.type.EnumTypeHandler" 
                     javaType="com.yihaomen.mybatis.enums.Hobby"/>
     <typeHandler handler="com.yihaomen.mybatis.type.MyMemberTypeHandler"
     javaType="com.yihaomen.mybatis.enums.Member"/>
</typeHandlers>

 

测试一下:

package user;

import com.yihaomen.mybatis.dao.UserMapper;
import com.yihaomen.mybatis.enums.Gender;
import com.yihaomen.mybatis.enums.Hobby;
import com.yihaomen.mybatis.enums.Member;
import com.yihaomen.mybatis.model.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Date;
import java.util.List;

/**
*   
*  @ProjectName: springmvc-mybatis 
*  @Description:
*/
public class TestEnumUser extends BaseTest{
public static void main(String[] args) {
// testAddEnum();
testGetEnumUser();
}

/**
* 添加
*/
public static void testAddEnum() {
SqlSession sqlSession = null;
try {
SqlSessionFactory sqlSessionFactory = getSession();
sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUserName("小明");
user.setGender(Gender.MALE);
user.setHobby(Hobby.FOOTBALL);
user.setMember(Member.FATHER);
user.setRegTime(new Date());
user.setUserAddress("地球");
user.setUserAge("22");
int result = mapper.addUser2(user);
System.out.println(result);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}

/**
* select
*/
public static void testGetEnumUser() {
SqlSession sqlSession = null;
try {
SqlSessionFactory sqlSessionFactory = getSession();
sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUserById2(11L);
for(User u : users) {
System.out.println(u.getGender());
System.out.println(u.getHobby());
System.out.println(u.getMember());
}
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}
}
 

https://gitee.com/huayicompany/springmvc-mybatis.git

参考文献:

 [1] 杨开振 著,《深入浅出MyBatis技术原理与实战》, 电子工业出版社,2016.09

posted @ 2017-10-15 18:21  寻找风口的猪  阅读(5099)  评论(0编辑  收藏  举报